<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Balance;
use App\Models\Withdraw;
use App\Services\BalanceService;
use Illuminate\Http\Request;
use Yansongda\Pay\Exceptions\GatewayException;

class WithdrawController extends BaseController
{

    public function index(Request $request) {
        $search = ['status' => -1, 'start_at' => '', 'end_at' => ''];
        $input = $request->input();
        $user_id = \request('user_id');
        $deal_start_at = $input['deal_start_at'] ?? null;
        $deal_end_at = $input['deal_end_at'] ?? null;
        $users = Withdraw::apply($search, $input)
            ->when($deal_start_at, function ($q) use($deal_start_at){
                $q->where('updated_at', '>=', $deal_start_at);
            })
            ->when($deal_end_at, function ($q) use($deal_end_at){
                $end_at = date('Y-m-d', strtotime($deal_end_at) + 24 * 3600);
                return $q->where('updated_at', '<', $end_at);
            })
            ->when($user_id, function ($q) use($user_id){
                return $q->where('user_id', '=', $user_id);
            })
            ->withCertain('user', [
                'nickname', 'avatar_url'
            ])
            ->with('bank')
            ->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($users);
    }

    public function handle(Request $request) {
        $this->validate($request, [
            'id' => 'required',
            'action' => 'required|in:pass,reject'
        ]);
        $input = $request->input();
        $model = Withdraw::find($input['id']);
        if (!$model)
            return $this->failed('提现id不存在');

        if ($model->status != Withdraw::STATUS_TO_DO)
            return $this->failed('当前状态不是待审核状态');


        if ($input['action'] == 'reject') {
            $model->reason = $input['reason'] ?? '';
            $model->status = Withdraw::STATUS_FAIL;
            $model->save();
            return $this->success([], '操作成功');
        } else {
            $model->reason = $input['reason'] ?? '';
            $model->status = Withdraw::STATUS_SUCCESS;
            $model->save();
            BalanceService::store($model->user_id, -$model->amount, Balance::TYPE_WITHDRAW, $model->id);
            return $this->success([], '操作成功');
        }

    }






}

